from flask import jsonify, request

from myApp.model.message_model import Message
from myApp.model.room_model import Room
from flask import Blueprint

# from myApp.utils.InitModel import run

room_db = Blueprint('room', __name__)


# 根据用户和房间获取消息
@room_db.route('/room/list', methods=['POST'])
def get_all_messages():
    data = request.json
    rooms = Room.get_active_rooms_by_user_id(data['user_id'])
    # 根据update_time排序
    rooms.sort(key=lambda x: x.update_time, reverse=True)
    return jsonify([room.serialize() for room in rooms]), 200


@room_db.route('/room/delete', methods=['POST'])
def delete_room():
    data = request.json
    type = data.get('type')
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    if type == "clear":
        Message.delete_message_by_room_id(room_id)
    if type == "del":
        Room.delete_room(room_id)
    if type == "delAll":
        Room.delete_room_user(user_id)

    return jsonify({'message': 'success'}), 200
